<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<x-status-bar></x-status-bar>
			<view class="flex-center-between header-navbar">
				<x-back-btn></x-back-btn>
				<view class="u-f-40 common-title">{{ lang_personal.shopCart }}</view>
				<view></view>
			</view>

			<!-- 管理商品 -->
			<view class="flex-center-between u-f-32 u-lh-44" style="padding: 22rpx 34rpx 32rpx;">
				<view class="flex-center linecamp-1" @click="getArea">
					<image src="@/static/image/personal/address@2x.png" style="width: 36rpx; height: 36rpx;"
						class="clear-flex"></image>

					<view class="u-m-l-20 linecamp-1">{{ areaFormat || lang_address.selectAddressTips }}</view>
				</view>

				<view class="font-medio linecamp-1" @click="changeStatus()">{{ isEdit ? lang_common.complete : lang_common.manager }}</view>
			</view>
		</view>

		<!-- 列表 -->
		<view>
			<mescroll-body height="calc(100vh - 344rpx - var(--status-bar-height))" ref="mescrollRef"
				@init="mescrollInit" @down="downCallback" @up="upCallback">
				<view v-for="(item, index) in dataList" :key="index" class="u-p-t-8">
					<view class="goods-card flex-center">
						<view class="flex-center-center">
							<x-checkbox v-model="item.checked"></x-checkbox>
						</view>
						<view class="u-m-l-24 flex-center" style="width: 100%;" @click="jumpUrl(`/pages/user/shop/detail/detail?goodsId=${ item.goodsId }`)">
							<view class="image-container clear-flex">
								<x-image :src="showImage(item.imgUrl, 'logo')"/>
							</view>
						
							<view class="u-m-l-24 flex-between flex-column" style="width: 100%;">
								<view class="u-f-28 u-lh-40 linecamp-2">{{ item.title || '' }}</view>
						
								<view class="u-m-t-4 u-f-26 u-lh-36 color-grew">{{ item.specs|| '' }}</view>
						
								<view :class="['u-m-p-16 flex-center-between']" style="width: 100%;">
									<view class="flex-baseline color-red">
										<view>{{ lang_unit.money }}</view>
										<view>{{ item.discountPrice || 0 }}</view>
									</view>
						
									<view v-if="item.stock" @click.stop>
										<u-number-box v-model="item.amount" button-size="22" :max="item.stock"
											@blur="changeCount(item)" @plus="changeCount(item)" @minus="changeCount(item)">
										</u-number-box>
									</view>
									<viwe v-else>{{ lang_goods.notStock }}</viwe>
								</view>
							</view>
						</view>
					</view>
				</view>
			</mescroll-body>
		</view>

		<!-- 提交操作 -->
		<x-fixed-bottom>
			<view class="flex-center-between" :style="{ padding: `26rpx 40rpx 32rpx` }">
				<view>
					<x-checkbox v-model="selectAll" @change="changeAll">
						<view class="u-m-l-18">{{ lang_common.selectAll }}</view>
					</x-checkbox>
				</view>

				<view v-show="isEdit" class="flex-center">
					<!-- <view class="u-m-r-12">
						<x-common-btn width="206" height="90" color="#333333" borderColor="#E9E9E9" borderWidth="2"
							background="#FFFFFF" @click="collectAction">
							<view>移入收藏夹</view>
						</x-common-btn>
					</view> -->

					<view>
						<x-common-btn width="206" height="90" background="#FD1E43" @click="deleteAction">
							<view>{{ lang_common.delete }}</view>
						</x-common-btn>
					</view>
				</view>

				<view v-show="!isEdit" class="flex-center">
					<view class="u-m-r-46 linecamp-1 nowrap">{{ lang_goods.countAll }}</view>

					<view class="flex-baseline u-m-r-34 u-lh-32 font-bold nowrap" style="color: #FE5521;">
						<view class="u-f-28">{{ lang_unit.money }}</view>
						<view class="u-f-44">{{ goodsPrice }}</view>
					</view>
					<view>
						<x-common-btn width="206" height="90" background="#FD1E43" @click="countAction">
							<view class="flex-center">
								<view class="clear-flex linecamp-1">{{ lang_goods.countGoods }}</view>
								<view class="clear-flex">({{ goodsCount }})</view>
							</view>
						</x-common-btn>
					</view>
				</view>
			</view>
		</x-fixed-bottom>
	</view>
</template>

<script>
	import {
		cartPage,
		cartAddOrUpdate,
		cartDeleteCart
	} from '@/api/user/shopcart.js'
	import {
		orderCreateCart
	} from '@/api/user/order.js'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";

	export default {
		mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
				isEdit: false,

				total: 0,
				dataList: [],

				checkboxs: [],
				selectAll: false,
				
				isClick: false
			}
		},
		computed: {
			goodsSelected() {
				return (this.dataList.filter(item => item.checked) || [])
			},
			goodsCount() {
				return this.goodsSelected.length
			},
			goodsPrice() {
				let total = 0;
				this.dataList.map(({
					amount,
					discountPrice,
					checked
				}) => {
					if (checked) {
						let goodsVal = Number(discountPrice || 0).mul(amount || 0)
						total = Number(total).add(goodsVal)
					}
				})
				return Number(total).formatMoney(total)
			},
			areaFormat() {
				let str = '',
					area = this.shopcartAddress || {}
				let keys = ['country', 'province', 'city', 'area', 'address']
				keys.map(item => {
					if (area[item]) {
						str+=area[item]
					}
				})
				console.log(str)
				return str
			}
		},
		watch: {
			goodsCount: {
				handler(v) {
					this.selectAll = this.total && this.goodsCount === this.total
				},
				immediate: true,
				deep: true
			}
		},
		onLoad() {
			// 假数据
			let goods = []
			for (let i = 0; i < 9; i++) {
				goods.push({
					price: Number((Math.random() * 1000 + 10).toFixed(2)),
					count: 1,
					checked: false
				})
			}
			this.goods = goods
		},
		methods: {
			// 修改地址
			getArea() {
				uni.navigateTo({
					url: '/pages/user/address/list/list?type=use',
					events: {
						changeAction: res => {
							this.$store.commit('UPDATE_USER_SHOP_CART_ADDRESS', res)
						}
					}
				})
			},
			// 选择全部
			changeAll(e) {
				this.dataList.map(item => {
					item.checked = e
				})
			},
			// 改变删除和结算的状态
			changeStatus() {
				this.$set(this, 'isEdit', !this.isEdit)
			},
			// 移入收藏夹
			collectAction() {
				if (!this.goodsCount) {
					return this.$api.msg(this.lang_common.unCheckTips)
				}
				// this.actionAction(4, { })
			},
			// 对商品进行结算
			countAction() {
				if (!this.goodsCount) {
					return this.$api.msg(this.lang_common.unCheckTips)
				}
				uni.navigateTo({
					url: `/pages/user/order/ready/ready`,
					success: res => {
						res.eventChannel.emit('order-ready', ({ type: 'shopcart', list: this.goodsSelected }))
					}
				})
			},
			// 对商品进行删除操作 
			deleteAction() {
				if (!this.goodsCount) {
					return this.$api.msg(this.lang_common.unCheckTips)
				}
				let cartIds = this.goodsSelected.map(item => item.cartId).join(',')
				if (this.isClick) return;
				this.isClick = true
				cartDeleteCart({
					cartIds
				}).then(() => {
					this.isClick = false
					this.$store.dispatch('initUserData')
					this.downCallback()
				}).catch(() => { this.isClick = false })
			},
			// 对商品进行增加或减少
			changeCount(item) {
				let {
					goodsId,
					specs,
					amount,
					originAmount,
					attrIds,
					goodsSpecAttributePriceId
				} = item || {}
				let count = originAmount - amount
				if (!count) return
				let type = count > 0 ? 2 : 1
				let queryObj = {
					goodsId,
					specs,
					amount: Math.abs(count),
					attrIds,
					goodsSpecAttributePriceId
				}
				cartAddOrUpdate({
					...queryObj,
					type
				}).then(result => {
					this.downCallback()
				})
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			upCallback(page) {
				let node = this.$refs['mescrollRef']
				let queryObj = {}
				cartPage({
					pageNumber: page.num,
					pageSize: page.size
				}).then(res => {
					node && node.mescroll.endSuccess(res.list.length);
					let goodsSelect = this.goodsSelected.map(item => item.cartId)
					if (page.num == 1) this.dataList = []; //如果是第一页需手动制空列表
					this.dataList = this.dataList.concat(res.list.map(item => ({
						...item,
						checked: goodsSelect.includes(item.cartId),
						originAmount: item.amount
					}))); //追加新数据
					this.total = res.totalRow || 0
				}).catch(() => {
					node && node.mescroll.endErr();
				})
			},
			downCallback() {
				let node = this.$refs['mescrollRef']
				node && node.mescroll.resetUpScroll()
			},
		}
	}
</script>

<style scoped lang="scss">
	.goods-card {
		padding: 48rpx 40rpx;
		background-color: #FFFFFF;
	}

	.image {
		&-container {
			width: 160rpx;
			height: 160rpx;
			background-color: #f9f9f9;
		}
	}
</style>
